package com.zzz.springcloud.controller;

import com.netflix.discovery.DiscoveryClient;
import com.zzz.springcloud.entity.CommonResult;
import com.zzz.springcloud.entity.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.netflix.eureka.EurekaDiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

@RestController
@Slf4j
public class OrderController {

    private final static String url = "http://CLOUD-PAYMENT-SERVICE";

    @Resource
    private EurekaDiscoveryClient discoveryClient;

    @Resource
    private RestTemplate restTemplate;

    @PostMapping("/order/get")
    public CommonResult<Payment> getOrder() {
        return restTemplate.getForObject(url + "/payment/get/1", CommonResult.class);
    }

    @GetMapping("/order/create")
    public CommonResult createOrder(Payment payment) {
        return restTemplate.postForObject(url + "/payment/add", payment, CommonResult.class);
    }


    @GetMapping("/order/serviceInfo")
    public Object discovery() {
        List<String> services = discoveryClient.getServices();
        services.forEach(e->log.info("**** element: " + e));

        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        instances.forEach(e -> log.info(e.getServiceId() + "\t" + e.getHost()+"\t"+e.getPort() +"\t" + e.getUri()));

        return this.discoveryClient;
    }

    @GetMapping("/consumer/payment/getForEntity/{id}")
    public CommonResult<Payment> getForEntity(@PathVariable("id") Long id) {
        ResponseEntity<CommonResult> forEntity = restTemplate.getForEntity(url + "/payment/get/" + id, CommonResult.class);
        if(forEntity.getStatusCode().is2xxSuccessful()) {
            return forEntity.getBody();
        }
        return new CommonResult<>(444, "获取结果失败");
    }
}
